package com.example.rabbitmqdemo.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeoutException;

/**
 * @author liujb
 * @description TODO
 * @date 2022-06-28 18:50
 */
public class RabbitmqUtils {

    private static final ConnectionFactory connectionFactory;

    static {
        // 创建连接MQ的连接工厂对象，重置级对象，类加载时创建一次即可
        connectionFactory = new ConnectionFactory();
        // 设置连接RabbitMQ的主机地址
        connectionFactory.setHost("192.168.25.111");
        // 设置端口号
        connectionFactory.setPort(5672);
        // 设置连接的虚拟主机
        connectionFactory.setVirtualHost("/dev");
        // 设置访问虚拟主机的用户名和密码
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
    }

    /**
     * 获取连接对象
     * @return RabbitMQ连接对象
     */
    public static Connection getConnection(){
        try {
            return connectionFactory.newConnection();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 关闭通道和连接
     * @param channel 通道
     * @param connection 连接
     */
    public static void close(Channel channel, Connection connection) {
        if (Objects.nonNull(channel)) {
            try {
                channel.close();
            } catch (IOException | TimeoutException e) {
                e.printStackTrace();
            }
        }
        if (Objects.nonNull(connection)) {
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
